import { handleActions as createReducer } from 'redux-actions';
import { EAT_APPLE, GET_APPLE, LOAD_APPLES, LOAD_APPLES_ASYNC } from '../actions/cart.actions';
const initialState = {
    isPicking: false,
    newAppleId: 0,
    apples: [],
    eatenApples: 0,
    curApples: 0
};

const apples = [{
    id: 0,
    weight: 233,
    isEaten: false
},
{
    id: 1,
    weight: 235,
    isEaten: true
},
{
    id: 2,
    weight: 256,
    isEaten: false
}];

const updateData = newState => {
    newState.curApples = 0;
    newState.eatenApples = 0;
    newState.apples.forEach(a => {
        a.isEaten ? newState.eatenApples++ : newState.curApples++;
    });
}

const handleLoadApples = (state, action) => {
    const newState = JSON.parse(JSON.stringify(state));
    newState.apples = apples;
    newState.newAppleId = newState.apples.length;
    updateData(newState);
    return newState;
}

const handleEatApple = (state, action) => {
    const newState = JSON.parse(JSON.stringify(state));
    newState.apples.forEach(a => {
        if (a.id === action.payload.id) a.isEaten = true;
    });
    updateData(newState);
    return newState;
}

const handleGetApple = (state, action) => {
    const newState = JSON.parse(JSON.stringify(state));
    let apple = {
        id: newState.apples.length + 1,
        weight: 230 + newState.apples.length + 1,
        isEaten: false
    }
    newState.apples.push(apple);
    updateData(newState);
    return newState;
}

const handleLoadCarts = (state, action) => {
    const newState = JSON.parse(JSON.stringify(state));
    newState.apples = action.payload;
    newState.newAppleId = newState.apples.length;
    updateData(newState);
    return newState;
}

export default createReducer({
    [LOAD_APPLES]: handleLoadApples,
    [EAT_APPLE]: handleEatApple,
    [GET_APPLE]: handleGetApple,
    [LOAD_APPLES_ASYNC]: handleLoadCarts
}, initialState)